<?php

namespace App\Models\Factory;

use App\Helpers\Utils;
use App\Helpers\DateUtils;
use App\Helpers\RestUtils;
use App\Helpers\Logger\SLogger;
use App\Helpers\Generator\TokenGenerator;
use App\Models\AbsModelFactory;
use App\Models\Orm\User;
use App\Models\Orm\VipLog;
use App\Models\Orm\PaySetting;
use App\Models\Orm\OrderInternal;
use App\Models\Factory\UserFactory;
use App\Models\Factory\FreeDoubleFactory;
use Yansongda\Pay\Pay;
use Yansongda\Pay\Log;
use DB;

/**
 * 下单支付工厂
 * Class PayFactory
 * @package App\Models\Factory
 */
class PayFactory extends AbsModelFactory
{

	/**
	 * 共有的验证方法
	 */
	private static function checkout($orderid,$money,$userinfo,$res)
	{
		if(empty($orderid) || empty($money)){
       		return 4000;
        }

        if(empty($userinfo)){
       		return 1003;
        }

        //验证订单是否存在
        if(empty($res)){
        	return 4000;
        }

        //验证订单金额是否正确
        if($res['0']['amount'] != $money){
        	return 5000;
        }

        return 1;
	}


	/**
	 * 微信app支付
	 */
    public static function wxPayApp($request,$token)
    {
        $orderid = $request['orderid'] ? : "";
        $money   = (int)$request['money'] ? : 0;

        //获取用户信息
        $userinfo = UserFactory::getUserByToken($token);

        //查询订单
        $res = VipLog::where("order_id",$orderid)->where("user_id",$userinfo->id)->where("amount",$money)->where("status",1)->get()->toArray();
        
        $code = self::checkout($orderid,$money,$userinfo,$res);

        if($code!=1){
        	return $code;
        }

        //查询支付配置
        $pay = PaySetting::where("status",1)->where("type",1)->limit(1)->get()->toArray();

    		$order = [
    			'out_trade_no' => $orderid,
    			'total_fee'    => $money*100, // **单位：分**
    			'body'         => '幸运购'
        ];

        $config = [
            'appid'      => $pay['0']['extend'], // APP APPID
            'mch_id'     => $pay['0']['mid'],
            'key'        => $pay['0']['key'],
            'notify_url' =>  $_SERVER['HTTP_HOST'].'/v1/pay/wxappnotify'
        ];
        $info = Pay::wechat($config)->app($order);
        $arr = (array)$info;

        foreach($arr as $key => $val){
          $result[]=json_decode($val,true);
        }
        return $result[0];
    }



    /**
     * 支付宝app支付
     */
  	public static function aliPayApp($request,$token)
  	{
      

  		$orderid = $request['orderid'] ? : "";
        $money   = (int)$request['money'] ? : 0;

        //获取用户信息
        $userinfo = UserFactory::getUserByToken($token);

        //查询订单
        $res = VipLog::where("order_id",$orderid)->where("user_id",$userinfo->id)->where("amount",$money)->where("status",1)->get()->toArray();
        
        $code = self::checkout($orderid,$money,$userinfo,$res);

        if($code!=1){
        	return $code;
        }

        //查询支付配置
        $pay = PaySetting::where("status",1)->where("type",2)->limit(1)->get()->toArray();

    		$config = [
          'app_id'         => $pay['0']['mid'],
          'notify_url'     => $_SERVER['HTTP_HOST'].'/v1/pay/alinotify',
          'ali_public_key' => $pay['0']['extend'],
        // 加密方式： **RSA2**  
        'private_key' => $pay['0']['key'],
    		];

    		$order = [
            'out_trade_no' => $orderid,
            'total_amount' => $money.".00",
            'subject'      => '幸运购',
    		];
    		$info = Pay::alipay($config)->app($order);
        unset($info->headers);

        $arr = (array)$info;

        foreach($arr as $key => $val){
          $data[] = $val;
        }
        $solve = explode('&', $data['0']);
        $result=array();
        foreach($solve as $key => $val){
          $transition = array();
          $transition =explode('=', $val);

          $result[$transition['0']] = $transition['1'];

        }
        return $result;    
    		
  	}


  	/**
  	 * 微信H5支付
  	 */
  	public static function wxPayH($request,$token)
  	{
  		  $orderid = $request['orderid'] ? : "";
        $money   = (int)$request['money'] ? : 0;

        //获取用户信息
        $userinfo = UserFactory::getUserByToken($token);

        //查询订单
        $res = VipLog::where("order_id",$orderid)->where("user_id",$userinfo->id)->where("amount",$money/100)->where("status",1)->get()->toArray();
        
        $code = self::checkout($orderid,$money/100,$userinfo,$res);

        if($code!=1){
        	echo "<button onclick='javascript:history.go(-1)' style='width:100px; height:50px; lineheight:50px;display: block; margin: 20px auto;'>返回上一页</button>";die;
        }

  		 //查询支付配置
        $pay = PaySetting::where("status",1)->where('type',3)->limit(1)->get()->toArray();
        
        $config = [
          'appid'      => $pay['0']['extend'], // APP APPID
    			'app_id'     => $pay['0']['extend'], // 公众号 APPID
    			'mch_id'     => $pay['0']['mid'],
    			'key'        => $pay['0']['key'],
    			'notify_url' => $_SERVER['HTTP_HOST'].'/v1/pay/wxnotify'
    		];

      	$order = [
            'out_trade_no' => $orderid,
            'total_fee'    => $money,
            'body'         => '幸运购'
    		];

		    $info = Pay::wechat($config)->wap($order);
        
        echo $info;die;
  	}


  	/**
  	 * 微信公众号支付
  	 */
  	public static function wxPublicPay($request,$token)
  	{
  		  $orderid = $request['orderid'] ? : "";
        $money   = (int)$request['money'] ? : 0;

        //获取用户信息
        $userinfo = UserFactory::getUserByToken($token);

        //查询订单
        $res = VipLog::where("order_id",$orderid)->where("user_id",$userinfo->id)->where("amount",$money)->where("status",1)->get()->toArray();
        
        $code = self::checkout($orderid,$money,$userinfo,$res);

        if($code!=1){
        	return $code;
        }

        //查询支付配置
        $pay = PaySetting::where("status",1)->where('type',3)->limit(1)->get()->toArray();

      	$order = [
            'out_trade_no' => $orderid,
            'body'         => '幸运购',
            'total_fee'    => $money*100,
            'openid'       => 'o9Fz6wzQwYXSFhdyADRnHKuSrpxc',
    		];
        
        $config = [
    			'app_id'     => $pay['0']['extend'], // 公众号 APPID
    			'mch_id'     => $pay['0']['mid'],
    			'key'        => $pay['0']['key'],
    			'notify_url' => $_SERVER['HTTP_HOST'].'/v1/pay/wxnotify',
    		];


		    $info = Pay::wechat($config)->mp($order);
        $result = json_decode($info,true);
        return $result ? : array();
  	}


  	/**
  	 * 支付宝H5支付
  	 */
  	public static function aliPayH($request,$token)
  	{
  		  $orderid = $request['orderid'] ? : "";
        $money   = (int)$request['money'] ? : 0;

        //获取用户信息
        $userinfo = UserFactory::getUserByToken($token);

        //查询订单
        $res = VipLog::where("order_id",$orderid)->where("user_id",$userinfo->id)->where("amount",$money)->where("status",1)->get()->toArray();
        
        $code = self::checkout($orderid,$money/100,$userinfo,$res);

        if($code!=1){
        	echo "<button onclick='javascript:history.go(-1)' style='width:100px; height:50px; lineheight:50px;display: block; margin: 20px auto;'>返回上一页</button>";die;
        }

        //查询支付配置
        $pay = PaySetting::where("status",1)->where("type",2)->limit(1)->get()->toArray();

      	$config = [
            'app_id'         => $pay['0']['mid'],
            'notify_url'     => $_SERVER['HTTP_HOST'].'/v1/pay/alinotify',
            'ali_public_key' => $pay['0']['extend'],
            'private_key'    => $pay['0']['key'],
    		];

    		$order = [
            'out_trade_no' => $orderid,
            'total_amount' => $money,
            'subject'      => '幸运购',
    		];

    		$result = Pay::alipay($config)->wap($order);
    		echo $result;die;
 	  }

    /**
     * vip用户支付日志更新
     *
     */
    public static function operation($orderid,$type)
    {
        if(empty($orderid)){
          return false;
        }
        DB::beginTransaction();
        try{
          $log = VipLog::where("order_id",$orderid)->where("status",1)->get()->toArray();
          //流水不存在
          if(empty($log)){
            DB::rollBack();
            return false;
          }

          //查找用户信息 对象
          $userinfo = User::where("id",$log['0']['user_id'])->first();
          if(empty($userinfo)){
            DB::rollBack();
            return false;
          }

          //更改流水表的状态
          $save_log['pay_method']   = $type;
          $save_log['status']       = 2;
          $save_log['success_time'] = date("Y-m-d H:i:s");

          $cVipsta = VipLog::where("order_id",$orderid)->update($save_log);

          // 用户vip充值成功后将用户升级为vip并更新vip过期时间
          $userinfo->vip_level = 1;
          $userinfo->vip_expiration = date("Y-m-d H:i:s", strtotime("1 year"));
          $cUservip = $userinfo->save();

          if (!$cVipsta || !$cUservip) {

            DB::rollback();

            SLogger::getStream()->error('ID '.$userinfo->id.' 用户购买vip失败');

          }
          else
          {
            

            /**
            * 用户成为vip后，在彩票创建用户，并先赠送一注
            */ 
            $mobile = $userinfo->userphone;
            // 声明彩票用户注册渠道
            $nid = 'anwenqianbao';
            $token = TokenGenerator::generateToken(32);

            $user = app('db')->connection("mysql_lottery")->select("select * from user where mobile = '".$mobile."'");


            // 获取彩票 anwenqianbao 渠道信息
            $channel = app('db')->connection("mysql_lottery")->select("select * from delivery where nid = '".$nid."'");
            $channel = $channel[0] ?? [];

            if(!$user){

                $userInfo = [
                    "幸运彩" . rand(10000000, 99999999),
                    $mobile,
                    $token,
                    1,
                    $userinfo->terminal == 1 ? 2 : ($userinfo->terminal == 2 ? 1 : 3),
                    $channel->nid ?? $nid,
                    $channel->title ?? '',
                    DateUtils::getToday(),
                    Utils::ipAddress()
                ];

                $create_lotteryUser = app('db')->connection("mysql_lottery")->insert('insert into user ( user_name,mobile,token,project,terminal,channel_nid,channel_title,created_at,created_ip) values (?,?,?,?,?,?,?,?,?)', $userInfo);
                if($create_lotteryUser){

                    // 彩票用户创建成功统计彩票用户渠道注册
                    $user = app('db')->connection("mysql_lottery")->select("select * from user where mobile = '".$mobile."'");
                    // 注册渠道统计数据
                    $channelData = [
                        $channel->id ?? '',
                        $channel->nid ?? $nid,
                        time(),
                        2,
                        $user[0]->id ?? '',
                        DateUtils::getToday(),
                        Utils::ipAddress()
                    ];
                    $insertDeliverylLog = app('db')->connection("mysql_lottery")->insert('insert into delivery_log (channel_id,channel_nid,create_time,type,user_id,create_date,create_ip) values (?,?,?,?,?,?,?)', $channelData);
                    
                    /**
                    * vip用户赠送一注彩票
                    */ 
                    // 获取可投注奖期

                     $phase = app('db')->connection("mysql_lottery")->select("select phase from award_period where end_time > '".date("Y-m-d H:i:s",time())."' and lotid = 'ssq' and status = 1 order by end_time asc limit 1");
                     if(!$phase){
                        $phase = app('db')->connection("mysql_lottery")->select("select phase from award_period where lotid = 'ssq' order by created_at desc limit 1");
                     }
                     $phase = $phase[0]->phase ?? '';

                     //彩票订单ID
                    $internal_order = time().rand(11111111,99999999);

                    // 获取双色球随机一注号码
                    $data[]=Utils::randDouble();

                    // 创建彩票订单数据
                    $orderData = [
                        json_encode($data),
                        '101',
                        $user[0]->id ?? '',
                        $phase,
                        2,
                        2,
                        date("Y-m-d H:i:s"),
                        date("Y-m-d H:i:s"),
                        2,
                        'ssq',
                        1,
                        $internal_order
                    ];

                    $insertLotteryOrder = app('db')->connection("mysql_lottery")->insert('insert into order_internal (data,play_type,user_id,start_periods,pay_money_total,is_lunxun,created_at,updated_at,status,lotid,multiple,order_id) values (?,?,?,?,?,?,?,?,?,?,?,?)', $orderData);

                    if($insertLotteryOrder){
                        // 创建安稳钱包双色球赠送记录
                        $doubleData = [
                            'user_id'        => $userinfo->id ?? '',
                            'lottery_userId' => $user[0]->id ?? '',
                            'order_id'       => $internal_order,
                            'bonuscode'      => $data[0],
                            'phase'          => $phase,
                            'created_at'     => date("Y-m-d H:i:s")
                        ];
                        $createDoubleLog = FreeDoubleFactory::createDoubleLog($doubleData);

                    }else{

                        SLogger::getStream()->error('ID '.$userinfo->id.' 用户首次赠送双色球失败');

                    }
                    



                }
            }

            DB::commit();
            return true;
          }
        }catch(\Exception $e){
          DB::rollBack();
        }

    }

}
